﻿using AdventureWorks.Domain;
using System.Linq;
using AdventureWorks.DataAccess.SearchCriterias;
using NHibernate.Linq;
using AdventureWorks.DataAccess.Utils;
using NHibernate;
namespace AdventureWorks.DataAccess.repository
{
    public class VendorRepository : IVendorRepository
    {
        public IQueryable<Vendor> GetVendors(ISession session, VendorSearchCriteria searchCriteria)
        {
            return session.Query<Vendor>()
                .NullableWhere(x => x.Name == searchCriteria.Name)
                .NullableWhere(x => x.AccountNumber == searchCriteria.AccountNumber)
                .NullableWhere(x => x.CreditRating == searchCriteria.CreditRating)
                .NullableWhere(x => x.Active == searchCriteria.Active)
                .NullableWhere(x => x.PreferredVendorStatus == searchCriteria.PreferredVendorStatus);
        }


        public void SaveVendor(ISession session, Vendor vendor)
        {
            if (vendor.Id > 0)
            {
                var savedVendor = session.Get<Vendor>(vendor.Id);
                savedVendor.CreditRating = vendor.CreditRating;
                savedVendor.AccountNumber = vendor.AccountNumber;
                savedVendor.Active = vendor.Active;
                savedVendor.Name = vendor.Name;
                savedVendor.PreferredVendorStatus = vendor.PreferredVendorStatus;
                session.SaveOrUpdate(savedVendor);
            }
            else
                session.SaveOrUpdate(vendor);
        }
    }
}
